include GeoHelper
class Restaurant < ActiveRecord::Base
  #using_access_control
  has_one :account, :as => :user, :validate => true, :dependent => :delete
  has_many :delivery_men, :dependent => :delete_all
  has_many :orders
  has_many :pizza_makers

  validates_presence_of :name, :address, :phonenumber
  validates_uniqueness_of :address, :phonenumber
  validates_numericality_of :phonenumber, :only_integer => true
  validates_each :address do |record, attr, value|
    geocode = Geocoding.get(value)
    if geocode[0]
      record.latitude = geocode[0][:latitude]
      record.longitude = geocode[0][:longitude]
    else
      record.errors.add attr, "Errore nell'indirizzo!"
    end
  end

  def Restaurant.nearest_restaurant(latitude, longitude)
    nearest = Restaurant.first
    nearest_dist = sqrt(distance_km_from_degrees(abs(nearest.latitude - latitude))^2 +
                  distance_km_from_degrees(abs(nearest.longitude - longitude))^2)
    Restaurant.all[1..-1].each do |r|
      dist = sqrt(distance_km_from_degrees(abs(r.latitude - latitude))^2 +
                  distance_km_from_degrees(abs(r.longitude - longitude))^2)
      if dist < nearest_dist
        nearest = r
        nearest_dist = dist
      end
    end
    return nearest
  end
end
